package src.linkeLlist;

public class no21 {
    //合并两个有序链表

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode(0);  //定义虚拟头node，方便返回
        ListNode pre = dummy;  //用pre指针去连结点。而不是定义待连接的后一个结点

        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                pre.next = list1;
                list1 = list1.next;
            } else {
                pre.next = list2;
                list2 = list2.next;
            }
            pre = pre.next;
        }
        if (list1 != null) {
            pre.next = list1;
        }
        if (list2 != null) {
            pre.next = list2;
        }
        return dummy.next;

    }

    //递归
    public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }else if (list2 == null) {
            return list1;
        } else if (list1.val<=list2.val) {
            list1.next=mergeTwoLists2(list1.next,list2);
            return list1;
        }else {
            list2.next=mergeTwoLists2(list1,list2.next);
            return list2;
        }
    }

}
